from flask import request, jsonify, Blueprint
from app import db, LogService
from app.models import Train
from app.models.train_lib import buildTrain
from presenter.train import TrainPresenter
from utils import create_response, StateCode

trains_bp = Blueprint('trains', __name__)


@trains_bp.route('/trains', methods=['GET'])
def queryAllTrains():
    trains = Train.query.all()
    trains_presenters = [TrainPresenter(train).as_dict() for train in trains]
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=trains_presenters)), 200


@trains_bp.route('/trains', methods=['POST'])
def createTrain():
    data = request.json
    new_train = buildTrain(data)
    db.session.add(new_train)
    db.session.commit()
    train_presenter = TrainPresenter(new_train).as_dict()
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=train_presenter)), 200
